package com.io;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
 
public class HttpServer {
 
	public static void main(String[] args) throws Exception{
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.socket().bind(new InetSocketAddress(8080));
		ssc.configureBlocking(false);//非阻塞
		//为ssc注册选择器
		Selector selector = Selector.open();
		ssc.register(selector, SelectionKey.OP_ACCEPT);
		while(true){
			if(selector.select(3000) == 0){
				continue;
			}
			
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey key = it.next();
				//启动新线程处理SelectionKey
				new Thread(new HttpHandler(key)).run();
				it.remove();
			}
		}
 
	}
	private static class HttpHandler implements Runnable{
		private int bufferSize = 1024;
		private String localChatset ="UTF-8";
		SelectionKey key;
		public HttpHandler(SelectionKey key) {
			this.key = key;
		}
		public void handleAccept() throws IOException{
			SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
			channel.configureBlocking(false);
			channel.register(key.selector(), SelectionKey.OP_READ, 
					ByteBuffer.allocate(bufferSize));
		}
		
		public void handleRead() throws IOException{
			SocketChannel channel = (SocketChannel) key.channel();
			ByteBuffer buffer = (ByteBuffer) key.attachment();
			buffer.clear();
			if(channel.read(buffer) == -1){
				channel.close();
			}else{
				//将buffer转换为读状态
				buffer.flip();
				String receiveMsg = Charset.forName(localChatset).newDecoder().decode(buffer).toString();
				System.out.println("收到数据：" + receiveMsg);
				
				//返回数据给客户端
				StringBuilder sendMsg = new StringBuilder();
				sendMsg.append("HTTP/1.1 200 OK\r\n");
				sendMsg.append("content-type:text/html;charset=" + localChatset
						+ "\r\n");
				sendMsg.append("\r\n");
				sendMsg.append("现在内容将呈现在浏览器中");//响应体
				
				
				ByteBuffer buffer2 = ByteBuffer.wrap(sendMsg.toString().getBytes());
				channel.write(buffer2);
				channel.close();
			}
		}
		@Override
		public void run() {
			try {
				if(key.isAcceptable()){
					handleAccept();
				}
				if(key.isReadable()){
					handleRead();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
 
}
